package com.swak.algs.paxos;

import java.util.Queue;

import com.swak.algs.paxos.NetWork.Task;
import com.swak.utils.Queues;

public abstract class IoEvent implements Runnable {

	private Queue<Task> tasks = Queues.newArrayBlockingQueue(2000);

	Thread thread;

	public void onPrepare(Proposal proposal) {

	}

	public void PrepareResponse(PrepareResult proposalResult) {

	}

	public void onAccept(Proposal proposal) {

	}

	public void AcceptResponse(AcceptResult proposalResult) {

	}

	public IoEvent() {
		thread = new Thread(this);
		thread.setDaemon(false);
		thread.start();
	}

	public void addTask(Task task) {
		tasks.add(task);
	}

	@Override
	public void run() {

		while (true) {

			/*
			 * 获取任务
			 */
			Task task = tasks.poll();
			if (task == null) {
				continue;
			}

			Object v = task.v;

			// 准备阶段
			if (v instanceof Proposal && ((Proposal) v).getStep() == 1) {
				this.onPrepare(((Proposal) v));
			}

			// 准备阶段 -- 响应
			else if (v instanceof PrepareResult) {
				this.PrepareResponse(((PrepareResult) v));
			}

			// 接受阶段 -- 响应
			else if (v instanceof Proposal && ((Proposal) v).getStep() == 2) {
				this.onAccept(((Proposal) v));
			}

			// 接受阶段 -- 响应
			else if (v instanceof AcceptResult) {
				this.AcceptResponse(((AcceptResult) v));
			}

			/*
			 * 100ms 的延迟
			 */
			try {
				Thread.sleep(100);
			} catch (InterruptedException e) {
			}
		}
	}
}
